package com.example.wangyi.mvp.presenter;

import com.example.wangyi.base.BasePresenter;
import com.example.wangyi.base.BaseView;
import com.example.wangyi.callback.RxObserverCallBack;
import com.example.wangyi.constants.ApiConstants;
import com.example.wangyi.mvp.model.RxOpretorImpl;
import com.example.wangyi.mvp.model.bean.HomeBean;
import com.example.wangyi.utils.GsonUtils;
import com.google.gson.Gson;

import java.io.IOException;

import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

public class HomePresenter extends BasePresenter {
    private BaseView view;
    private final RxOpretorImpl rxOpretor;

    public HomePresenter(BaseView view) {
        this.view = view;
        rxOpretor = new RxOpretorImpl();
    }

    @Override
    public void start() {
        super.start();
        rxOpretor.rxGetRequest(ApiConstants.HOME_INDEX_URL, new RxObserverCallBack() {
            @Override
            public void onSuccessData(Object o) {
                ResponseBody body= (ResponseBody) o;
                try {
                    String string = body.string();
                    if(view!=null){
                        HomeBean homeBean = new Gson().fromJson(string, HomeBean.class);
//                        HomeBean homeBean = GsonUtils.jsonStr2Bean(string, HomeBean.class);
                        view.onSuccess(homeBean);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    if(view!=null){
                        view.onError(e.getMessage());
                    }
                }

            }

            @Override
            public void onErrorMsg(String msg) {
                if(view!=null){
                    view.onError(msg);
                }
            }

            @Override
            public void onSubscribe(Disposable disposable) {

            }
        });
    }
}
